package com.jinzhi.jzdoor.certificate.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.api.exception.IFastApiException;
import com.jinzhi.api.pojo.vo.TokenVO;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.domain.DictDO;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.type.ApiEnumError;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.*;
import com.jinzhi.jzapi.certificate.pojo.ExpertsVo;
import com.jinzhi.jzdoor.certificate.pojo.TrainingBaseVo;
import com.jinzhi.jzdoor.certificate.service.SmsLimitService;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.sms.config.SmsBasicConfigProperties;
import com.jinzhi.sms.support.SmsManager;
import com.jinzhi.sys.domain.RoleDO;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.domain.UserRoleDO;
import com.jinzhi.sys.service.RoleService;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import com.jinzhi.sys.shiro.PhoneAndVerificationCodeToken;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.jinzhi.api.util.TokenTag.TOKEN_TAG;

@Slf4j
@Controller
@AllArgsConstructor
@RequestMapping("/certificate")
@Api(tags = "首页")
public class IndexController extends BaseController {

    @Autowired
    private ConsultationsService consultationsService;
    @Autowired
    private CertificateNewsService certificateNewsService;
    @Autowired
    private EvaluationService evaluationService;
    @Autowired
    private UserService userService;
    @Autowired
    private ExpertsService expertsService;
    @Autowired
    private CertificationBatchService certificationBatchService;
    @Autowired
    private KnowledgePointsService knowledgePointsService;
    @Autowired
    private SmsManager smsService;
    @Autowired
    private MessageplatfromService messageplatfromService;
    @Autowired
    private MsgService msgService;
    @Autowired
    private DictService dictService;
    @Autowired
    private InfoStoreService infoStoreService;
    @Autowired
    private InfoModelService infoModelService;
    @Autowired
    private InfoCollectService infoCollectService;
    @Autowired
    private PeixunStudyService peixunStudyService;
    @Autowired
    private ResumesService resumesService;
    @Autowired
    private PeixResumeCollectService peixResumeCollectService;

    @Autowired
    private IndexService indexService;

    @Autowired
    private LeavingAMessageService leavingAMessageService;

    private static final String T_REG_SMS_PREFIX = "TRAINING_REG_";//培训端
    private static final String C_REG_SMS_PREFIX = "CERTIFICATE_REG_";//证书端
    private static final String O_REG_SMS_PREFIX = "ORTHER_REG_";//其他端

    public static final String prefix = "xn";


    @Log("证书门户首页")
    @GetMapping("/homepage")
    String homepage() {
        return "certificateWeb/homepage/homepage";
    }


    @Log("证书门户首页")
    @GetMapping("/homepage2")
    String homepage2() {
        return "certificateWeb/homepage/homepage2";
    }


    @Log("企业注册")
    @GetMapping("/enterpriseReg")
    String enterpriseReg(Model model, String id, String mobile, String name, String enId) {
        // UserDO userDO = userService.selectById(id);
        model.addAttribute("id", id);
        model.addAttribute("name", name);
        model.addAttribute("mobile", mobile);
        model.addAttribute("enId", enId);
        return "certificateWeb/enterpriseReg";
    }

    @Log("证书门户通知公告")
    @GetMapping("/inform")
    String inform(Model model) {
        Wrapper<ConsultationsDO> consultationsDOWrapper = new EntityWrapper<ConsultationsDO>().orderBy("creater_date", false);
        consultationsDOWrapper.eq("first_column", "证书考试门户");
        consultationsDOWrapper.eq("state", 1);
        consultationsDOWrapper.eq("second_column", "通知公告");

        List<ConsultationsDO> consultationsDOList = consultationsService.selectList(consultationsDOWrapper);
        model.addAttribute("consultations", consultationsDOList);
        return "certificateWeb/inform/inform";
    }

    @Log("通知公告详情")
    @GetMapping("/informDetail")
    String informDetail(Model model, Long id) {
        ConsultationsDO consultations = consultationsService.selectById(id);
        consultations.setAccessNumber(consultations.getAccessNumber() + 1);
        consultationsService.updateById(consultations);
        model.addAttribute("consultations", consultations);
        return "certificateWeb/inform/informDetail";
    }

    @Log("考务员信息填写")
    @GetMapping("/trainStudentInfo")
    String KWInfo() {
        return "certificateWeb/trainStudentInfo";
    }

    @Log("证书标准信息页面")
    @GetMapping("/certificateInfo")
    String certificateInfo() {
        return "certificateWeb/workNews/certificateInfo";
    }


    @Log("行业资讯")
    @GetMapping("/tradeInfo")
    String tradeInfo() {
        return "certificateWeb/tradeInfo/tradeInfo";
    }

    @Log("移动端行业资讯")
    @GetMapping("/tradeInfoMobile")
    String tradeInfoMobile() {
        return "certificateWeb/tradeInfo/tradeInfoMobile";
    }

    @Log("政策资讯")
    @GetMapping("/policyInfo")
    String policyInfo(Model model,HttpServletRequest request) {
        model.addAttribute("name", request.getParameter("name"));
        return "certificateWeb/tradeInfo/policyInfo";
    }

    @Log("移动端政策资讯")
    @GetMapping("/policyInfoMobile")
    String policyInfoMobile() {
        return "certificateWeb/tradeInfo/policyInfoMobile";
    }

    @Log("通知通告")
    @GetMapping("/noticeInfo")
    String noticeInfo() {
        return "certificateWeb/tradeInfo/noticeInfo";
    }

    @Log("移动端通知通告")
    @GetMapping("/noticeInfoMobile")
    String noticeInfoMobile() {
        return "certificateWeb/tradeInfo/noticeInfoMobile";
    }

    @Log("资讯详情")
    @GetMapping("/policyDetail")
    String policyDetail(Model model, Long id) {
        ConsultationsDO consultationsDO = consultationsService.selectById(id);
        consultationsDO.setAccessNumber(consultationsDO.getAccessNumber() + 1);
        consultationsService.updateById(consultationsDO);
        model.addAttribute("consultations", consultationsDO);
        return "certificateWeb/tradeInfo/policyDetail";
    }

    @Log("资讯详情移动端")
    @GetMapping("/policyDetailMobile")
    String policyDetailMobile(Model model, Long id) {
        ConsultationsDO consultationsDO = consultationsService.selectById(id);
        consultationsDO.setAccessNumber(consultationsDO.getAccessNumber() + 1);
        consultationsService.updateById(consultationsDO);
        consultationsDO.setContents(consultationsDO.getContents().replaceAll("width: ([0-9]*)px;", "width: 100%;"));
        model.addAttribute("consultations", consultationsDO);
        return "certificateWeb/tradeInfo/policyDetailMobile";
    }

    @Log("证书查询")
    @GetMapping("/certificateQuery")
    String certificateQuery() {
        return "certificateWeb/infoQuery/certificateQuery";
    }

    @Log("培训站点查询")
    @GetMapping("/testingCentreQueryPx")
    String testingCentreQueryPx() {
        return "certificateWeb/infoQuery/trainfoQuery";
    }

    @Log("考点查询")
    @GetMapping("/testingCentreQuery")
    String testingCentreQuery() {
        return "certificateWeb/infoQuery/testingCentreQuery";
    }


    @Log("专家查询")
    @GetMapping("/expertQuery")
    String expertQuery() {
        return "certificateWeb/infoQuery/expertQuery";
    }

    @Log("幼儿照护模拟考试页面")
    @GetMapping("/childExam")
    String childExam() {
        return "certificateWeb/personalCenter/childExam";
    }

    @Log("产后恢复模拟考试页面")
    @GetMapping("/recoverExam")
    String recoverExam() {
        return "certificateWeb/personalCenter/recoverExam";
    }

    @Log("专家条件查询")
    @PostMapping("/expertNameQuery")
    @ResponseBody
    Result<?> expertNameQuery(Model model, String type, String name, String current, String number) {
        Map map = new HashMap();
        if (type != null) {
            map.put("type", type);
        } else {
            map.put("type", null);
        }
        if (name.equals("")) {
            name = null;
        }
        map.put("name", name);
        Page<ExpertsVo> expertsVo = expertsService.selectListPage(Integer.parseInt(current), Integer.parseInt(number), map);

        List list = new ArrayList();
        for (int i = 0; i < expertsVo.getRecords().size(); i++) {
            ExpertsVo obj = (ExpertsVo) expertsVo.getRecords().get(i);
            if (obj.getKpointsId() != null) {
                KnowledgePointsDO knowledgePointsDO = knowledgePointsService.selectById(obj.getKpointsId());
                if (knowledgePointsDO != null) {
                    obj.setKpointsName(knowledgePointsDO.getName());
                }
            }
            list.add(obj);
        }
        expertsVo.setRecords(list);
        return Result.ok(expertsVo);
    }

    @Log("年份")
    @PostMapping("/selYearList")
    @ResponseBody
    Result<?> selYearList() {
        List<Map> list = new ArrayList<>();
        Long year = 2020l;
        LocalDate today = LocalDate.now();
        Integer years = today.getYear();

        while (year <= years.longValue()) {
            Map map = new HashMap();
            map.put("id", year);
            map.put("name", year);
            year++;
            list.add(map);
        }

        list.stream().sorted((a, b) -> Integer.valueOf(b.get("id").toString()) - Integer.valueOf(a.get("id").toString())).collect(Collectors.toList());

        return Result.ok(list);
    }


    @Log("成绩查询页面")
    @GetMapping("/gradeQuery")
    String gradeQuery() {
        return "certificateWeb/personalCenter/gradeQuery";
    }

    /**
     * 不需要简历投递收集信息
     *
     * @return
     */
    @GetMapping("/resumeCollect")
    @ResponseBody
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> resumeCollect(PeixResumeCollectDO peixResum, @RequestHeader(value = TOKEN_TAG, required = false) String token) {
        if (!StringUtil.notEmpty(token)) {
            return ApiResult.invalid();
        }
        UserDO user = this.getClientUser(token);
        if (user == null) {
            return ApiResult.invalid();
        }
        peixResum.setUserId(user.getId());
        peixResum.setCreateTime(new Date());
        boolean b = peixResumeCollectService.insert(peixResum);
        if (b) {
            return ApiResult.success();
        }
        return ApiResult.fail();

    }

    /**
     * 判断用户是否完善简历
     *
     * @return
     */
    @GetMapping("/isResumeUser")
    @ResponseBody
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public Result<?> isResumeUser(@RequestHeader(value = TOKEN_TAG, required = false) String token) {
        if (!StringUtil.notEmpty(token)) {
            return Result.fail();
        }
        UserDO user = this.getClientUser(token);
        if (user == null) {
            return Result.fail("出现错误了，请重新登录再试！");
        }
        ResumesDO resumesDO = resumesService.findOneByKv("user_id", user.getId());

        if (resumesDO != null) {
            return Result.ok(1);
        }
        return Result.ok(2);
    }


    /**
     * 判断用户是否填写过不需要推荐就业的反馈信息
     *
     * @return
     */
    @GetMapping("/feedbackList")
    @ResponseBody
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<Object> feedbackList(@RequestHeader(value = TOKEN_TAG, required = false) String token) {
        if (!StringUtil.notEmpty(token)) {
            return ApiResult.invalid();
        }
        UserDO user = this.getClientUser(token);

        if (user == null) {
            return ApiResult.invalid();
        }
        return ApiResult.success(1);
    }


    @Log("表单模板列表")
    @PostMapping("findInfoModelList")
    @ResponseBody
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    ApiResult<?> findInfoModelList(@RequestHeader(value = TOKEN_TAG, required = false) String token, Long infoStoreId) {
        if (!StringUtil.notEmpty(token)) {
            return ApiResult.invalid();
        }
        UserDO user = this.getClientUser(token);
        if (user == null) {
            return ApiResult.fail();
        }
        Wrapper<InfoModelDO> infoModelDOWrapper = new EntityWrapper<InfoModelDO>().orderBy("sort");
        infoModelDOWrapper.eq("info_store_id", infoStoreId);
        List<InfoModelDO> infoModelList = infoModelService.selectList(infoModelDOWrapper);
        InfoCollectDO infoCollectDO = infoCollectService.findOneByKv("user_id", user.getId(), "info_store_id", infoStoreId, "status", "0");
        Map map = new HashMap();
        map.put("infoModelList", infoModelList);
        if (infoCollectDO != null) {
            map.put("infoCollect", infoCollectDO);
        } else {
            map.put("infoCollect", null);
        }
        return ApiResult.success(map);
    }


    @Log("培训站点申请页面")
    @GetMapping("testingCentreApplyForPx")
    String testingCentreApplyForPx(Model model, Integer type) {

        //获取站点申请截止时间
        Map maps = new HashMap();
        maps.put("name", "培训基地申请截止时间");
        maps.put("type", "train_end_time");
        String applicationEndTime = dictService.selDicBy(maps);
        model.addAttribute("applicationEndTime", applicationEndTime);
        //考核站点申请截止标语
        Map mapss = new HashMap();
        mapss.put("name", "培训基地详申请截止标语");
        mapss.put("type", "train_slogan");
        String applicationSlogan = dictService.selDicBy(mapss);
        model.addAttribute("applicationSlogan", applicationSlogan);
        Map mapdic = new HashMap();
        mapdic.put("Type", "commitment");
        List<DictDO> doList = dictService.selectListBy(mapdic);
        if (doList.size() > 0) {
            model.addAttribute("commitment", doList.get(0).getValue());
        } else {
            model.addAttribute("commitment", "未设置");
        }

        return "certificateWeb/stationApplyFor/testingCentreApplyForPx";
    }


    ApiResult<?> selOrgInfo() {
        return ApiResult.success();
    }

    @Log("移动端培训站点申请页面")
    @GetMapping("testingPxMobile")
    String testingPxMobile(Model model, Integer type) {

        //获取站点申请截止时间
        Map maps = new HashMap();
        maps.put("name", "培训基地申请截止时间");
        maps.put("type", "train_end_time");
        String applicationEndTime = dictService.selDicBy(maps);
        model.addAttribute("applicationEndTime", applicationEndTime);
        //考核站点申请截止标语
        Map mapss = new HashMap();
        mapss.put("name", "培训基地详申请截止标语");
        mapss.put("type", "train_slogan");
        String applicationSlogan = dictService.selDicBy(mapss);
        model.addAttribute("applicationSlogan", applicationSlogan);
        Map mapdic = new HashMap();
        mapdic.put("Type", "commitment");
        List<DictDO> doList = dictService.selectListBy(mapdic);
        if (doList.size() > 0) {
            model.addAttribute("commitment", doList.get(0).getValue());
        } else {
            model.addAttribute("commitment", "未设置");
        }

        return "certificateWeb/stationApplyFor/testingPxMobile";
    }

    @Log("信息录入页面")
    @GetMapping("infoEnter")
    String infoEnter(Model model, String chatchId) {
        model.addAttribute("chatchId", chatchId);
        return "certificateWeb/onLineApply/infoEnter";
    }


    @Log("认证批次列表")
    @GetMapping("selectBatchList")
    @ResponseBody
    Result<?> selectBatchList(String current, String number) {
        Page<CertificationBatchDO> page = certificationBatchService.findListPage(Integer.parseInt(current), Integer.parseInt(number));
        return Result.ok(page);
    }


    @Log("跳转报名记录页面")
    @GetMapping("/findApplyExam")
    String findApplyExam() {
        return "certificateWeb/personalCenter/findApplyExam";
    }


    @Log("资料下载")
    @GetMapping("/dataDownload")
    String dataDownload() {
        return "certificateWeb/dataDownload/dataDownload";
    }

    @Log("资料文库详情")
    @GetMapping("/dataDetail")
    String dataDetail(Model model, Long id) {

        ConsultationsDO consultations = consultationsService.selectById(id);
        consultations.setAccessNumber(consultations.getAccessNumber() + 1);
        consultationsService.updateById(consultations);
        model.addAttribute("consultations", consultations);
        return "certificateWeb/dataDownload/dataDetail";
    }


    @Log("资料文库：职业技能等级标准")
    @GetMapping("/dataDownload/skillLeve")
    String skillLeve() {
        return "certificateWeb/dataDownload/skillLeve";
    }

    @Log("资料文库移动端：职业技能等级标准")
    @GetMapping("/dataDownload/skillLeveMobile")
    String skillLeveMobile() {
        return "certificateWeb/dataDownload/skillLeveMobile";
    }

    @Log("资料文库：教材配套资源")
    @GetMapping("/dataDownload/teaching")
    String teaching() {
        return "certificateWeb/dataDownload/teaching";
    }

    @Log("资料文库：教材配套资源")
    @GetMapping("/dataDownload/teachingMobile")
    String teachingMobile() {
        return "certificateWeb/dataDownload/teachingMobile";
    }

    @Log("资料文库：考核评分标准")
    @GetMapping("/dataDownload/scoreCriteria")
    String scoreCriteria() {
        return "certificateWeb/dataDownload/scoreCriteria";
    }

    @Log("资料文库：考评标准")
    @GetMapping("/dataDownload/evaluationCriteria")
    String evaluationCriteria() {
        return "certificateWeb/dataDownload/evaluationCriteria";
    }

    @Log("资料文库：课程标准")
    @GetMapping("/dataDownload/courseCriteria")
    String courseCriteria() {
        return "certificateWeb/dataDownload/courseCriteria";
    }

    @Log("资料文库：课程标准")
    @GetMapping("/dataDownload/courseCriteriaMobile")
    String courseCriteriaMobile() {
        return "certificateWeb/dataDownload/courseCriteriaMobile";
    }

    @Log("资料文库：操作手册")
    @GetMapping("/dataDownload/operationManual")
    String operationManual() {
        return "certificateWeb/dataDownload/operationManual";
    }

    @Log("资料文库：托育机构从业人员培训大纲")
    @GetMapping("/dataDownload/trainingProgram")
    String trainingProgram() {
        return "certificateWeb/dataDownload/trainingProgram";
    }

    @Log("资料文库：托育机构从业人员培训大纲")
    @GetMapping("/dataDownload/trainProgMobile")
    String trainProgMobile() {
        return "certificateWeb/dataDownload/trainProgMobile";
    }

    @Log("资料文库：其他资料")
    @GetMapping("/dataDownload/otherData")
    String otherData() {
        return "certificateWeb/dataDownload/otherData";
    }


    @Log("成绩分析")
    @GetMapping("/gradeAnalyze")
    String gradeAnalyze() {
        return "certificateWeb/workNews/gradeAnalyze";
    }


    @Log("标准信息详情")
    @GetMapping("/standardDetail")
    String standardDetail() {
        return "certificateWeb/workNews/standardDetail";
    }

    @Log("关于我们")
    @GetMapping("/certificateWeb")
    String certificateWeb() {
        return "certificateWeb/about";
    }

    @Log("关于我们移动端")
    @GetMapping("/aboutMobile")
    String aboutMobile() {
        return "certificateWeb/aboutMobile";
    }

    /**
     * 登录微信扫码登录跳转
     *
     * @param model
     * @return
     */
    @Log("跳转登录页面")
    @GetMapping("/loginWeb")
    String loginWeb(Model model) {
        String codeimg = null;

        try {
            //配置微信回调
            String urlString = URLEncoder.encode("https://www.jz1x.com/jzApi/wximgCode/wxlogCode", "utf-8");
            codeimg = "https://open.weixin.qq.com/connect/qrconnect?appid=wxa5b743d1daed59cc&redirect_uri=" + urlString + "&response_type=code&scope=snsapi_login&state=e97555458779708b99b9d40cb49f54245c7500e536445d32#wechat_redirect";

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //注册须知
        Wrapper<ConsultationsDO> consultationsDOWrapper = new EntityWrapper<ConsultationsDO>().orderBy("creater_date", false);
        consultationsDOWrapper.eq("first_column", "证书考试门户");
        consultationsDOWrapper.eq("state", 1);
        consultationsDOWrapper.eq("second_column", "注册须知").last("limit 1"); //只查询1条

        List<ConsultationsDO> consultationsDOList = consultationsService.selectList(consultationsDOWrapper);
        model.addAttribute("consultations", consultationsDOList);
        model.addAttribute("url", codeimg);

        return "certificateWeb/loginWeb";
    }

    /**
     * 培训就业账户判断
     *
     * @param username
     * @return
     */
    @Log("跳转到指定页面")
    @GetMapping("/studyLogin")
    String loginWeb(Model model, String username) {

        //注册须知
        Wrapper<PeixunStudyDO> wrapper = new EntityWrapper<PeixunStudyDO>();
        wrapper.eq("user_name", username); //只查询1条

        List<PeixunStudyDO> consultationsDOList = peixunStudyService.selectList(wrapper);

        if (consultationsDOList.size() > 0) {
            return "cultivateWeb/login";
        }


        return "cultivateWeb/login";
    }

    /**
     * 登录 ----手机号-密码
     *
     * @param req
     * @param username
     * @param password
     * @return
     */
    @Log("提交登录信息")
    @PostMapping("/sendLogin")
    @ResponseBody
    @ApiOperation(value = "手机号登录", notes = "手机号登录")
    @ApiResponses({@ApiResponse(code = 0, message = "操作成功"), @ApiResponse(code = 500, message = "服务器内部异常")})
    Result<Map> sendLogin(HttpServletRequest req, String username, String password, String identity) {
        // 校验参数
        if (StringUtils.isEmpty(username) && StringUtils.isEmpty(password)) {
            return Result.build(500, "账号密码不能为空");
        }

        String pass = MD5Utils.convertMD5(password);
        // 根据手机号查询用户
        EntityWrapper<UserDO> wrapper = new EntityWrapper<>();
        wrapper.eq("mobile", username);
        UserDO userDoQuery = userService.selectOne(wrapper);

        if (userDoQuery == null) {
            return Result.build(500, "账号不存在 请重新输入");
        }

        // 判断登录类型
        if (identity.equals("0")) {
            // 教师/管理员登录
            if (userDoQuery.getType().equals(5)) {
                // 类型不匹配
                return Result.build(EnumErrorCode.userNoFountFail.getCode(), EnumErrorCode.userNoFountFail.getMsg());
            }
        } else if (identity.equals("1")) {
            // 学生登录
            if (userDoQuery.getType().equals(3) || userDoQuery.getType().equals(4)) {
                // 类型不匹配
                return Result.build(EnumErrorCode.userNoFountFail.getCode(), EnumErrorCode.userNoFountFail.getMsg());
            }
        } else {
            return Result.build(EnumErrorCode.userNoFountFail.getCode(), EnumErrorCode.userNoFountFail.getMsg());
        }

        Map m = new HashMap();
        m.put("username", username);
        if (!userService.exist(m)) {
            UserDO users = userService.findOneByKv("mobile", username);
            if (users == null) {
                return Result.build(500, "账号不存在 请重新输入");
            }
            username = users.getUsername();
        }

        UsernamePasswordToken token = new UsernamePasswordToken(username, pass);
        //token.setRememberMe(false);//记住我是可选项，但只有会话缓存到redis等持久存储才能真正记住
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            UserDO userDO = (UserDO) subject.getPrincipals().getPrimaryPrincipal();
            //根据手机号码生成自定义登录态
            TokenVO returnToken = userService.getToken(userDO.getMobile());

            //将生成的登录态和手机号码关联，并存到缓存中
            Map cache = new HashMap();
            cache.put("mobile", userDO.getMobile());
            EhCacheUtil.put(returnToken.getToken(), cache);
            //返回登录态和用户信息
            Map<String, Object> map = new HashMap<>();
            map.put("token", returnToken.getToken());
            map.put("userName", userDO.getUsername());
            map.put("type", userDO.getType());
            map.put("userId", userDO.getId());
            map.put("mobile", userDO.getMobile());
            map.put("uName", userDO.getName());
            List<MsgDO> msg = msgService.findByKv("state", 0, "userId", userDO.getId(), "type", 0);
            List<MsgDO> msg1 = msgService.findByKv("state", 0, "userId", userDO.getId(), "type", 1);
            map.put("unreadNum0", msg.size());
            map.put("unreadNum1", msg1.size());
            req.getSession().setAttribute("userName", userDO.getUsername());
            //req.getSession().setAttribute("mobile", userDO.getMobile());

            return Result.ok(map);
        } catch (AuthenticationException e) {
            return Result.build(EnumErrorCode.userLoginFail.getCode(), EnumErrorCode.userLoginFail.getMsg());
        }
    }

    @Autowired
    private SmsManager smsSerevice;


    /**
     * 登录---手机号验证码登录
     *
     * @param req
     * @param username
     * @param code
     * @return
     */
    @Log("提交登录信息")
    @PostMapping("/sendPhoneLogin")
    @ResponseBody
    @ApiOperation(value = "验证码登录", notes = "验证码登录")
    @ApiResponses({@ApiResponse(code = 0, message = "操作成功"), @ApiResponse(code = 500, message = "服务器内部异常")})
    Result<?> sendLogin1(HttpServletRequest req, String username, String code, String identity) {
        // 校验参数
        if (StringUtils.isEmpty(username) && StringUtils.isEmpty(code)) {
            return Result.build(500, "手机号和验证码不能为空");
        }

        if (StringUtils.isBlank(code)) {
            return Result.build(EnumErrorCode.userLoginFai1l4.getCode(), EnumErrorCode.userLoginFai1l4.getMsg());
        } else {
            // 校验验证码是否失效
            boolean verifyCode = smsService.verifyCode(O_REG_SMS_PREFIX, username);
            if (verifyCode) {
                return Result.build(EnumErrorCode.userLoginFai1l2.getCode(), EnumErrorCode.userLoginFai1l2.getMsg());
            }
            //第二步，判断验证码
            try {
                smsSerevice.verify(O_REG_SMS_PREFIX, username, code);
            } catch (Exception e) {
                return Result.build(ApiEnumError.apiSmsCodeInvalid.getCode(), ApiEnumError.apiSmsCodeInvalid.getMsg());
            }
            //第三步，根据手机号码获取用户信息并判断
            UserDO userDOS = userService.findOneByKv("mobile", username);
            if (userDOS == null) {
                return Result.build(EnumErrorCode.userNoFountFail.getCode(), EnumErrorCode.userNoFountFail.getMsg());
            }

            // 存在，校验登录类型
            // 判断登录类型
            if (identity.equals("0")) {
                // 教师/管理员登录
                if (userDOS.getType().equals(5)) {
                    // 类型不匹配
                    return Result.build(EnumErrorCode.userNoFountFail.getCode(), EnumErrorCode.userNoFountFail.getMsg());
                }
            } else if (identity.equals("1")) {
                // 学生登录
                if (userDOS.getType().equals(3) || userDOS.getType().equals(4)) {
                    // 类型不匹配
                    return Result.build(EnumErrorCode.userNoFountFail.getCode(), EnumErrorCode.userNoFountFail.getMsg());
                }
            } else {
                return Result.build(EnumErrorCode.userNoFountFail.getCode(), EnumErrorCode.userNoFountFail.getMsg());
            }
            PhoneAndVerificationCodeToken token = new PhoneAndVerificationCodeToken(username);
            Subject subject = SecurityUtils.getSubject();

            subject.login(token);
            UserDO userDOs = (UserDO) subject.getPrincipals().getPrimaryPrincipal();

            //第四步，根据手机号码生成自定义登录态
            TokenVO returnToken = userService.getToken(username);
            //第五步，将生成的登录态和手机号码关联
            Map cache = new HashMap();
            cache.put("mobile", username);
            EhCacheUtil.put(returnToken.getToken(), cache);
            //第六步，返回登录态和用户信息
            Map<String, Object> map = new HashMap<>();
            map.put("token", returnToken.getToken());
            map.put("type", userDOS.getType());
            map.put("userId", userDOS.getId());
            map.put("userName", userDOS.getUsername());
            map.put("mobile", userDOS.getMobile());
            map.put("headPortrait", userDOS.getHeadPortrait());
            req.getSession().setAttribute("userName", userDOS.getUsername());
            return Result.ok(map);

        }
    }

    @Autowired
    StringRedisTemplate redisTemplate;
    private SmsBasicConfigProperties properties;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    @Log("提交注册")
    @PostMapping("/sendRegister")
    @ApiOperation(value = "用户注册", notes = "用户注册")
    @ApiResponses({@ApiResponse(code = 0, message = "操作成功"), @ApiResponse(code = 500, message = "服务器内部异常")})
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result<?> sendRegister(String name, String mobile, String type, String num,HttpServletRequest request) {
        String password = "123456";

        //查询手机号是否注册
        Wrapper<UserDO> wrapper = new EntityWrapper();
        wrapper.eq("mobile", mobile);
        UserDO user = userService.selectOne(wrapper);
        if (user != null) {
            return Result.fail("手机号已被注册");
            //throw new IFastApiException(EnumErrorCode.userLoginFai1l45.getCodeStr());
        }
        UserDO users = userService.findOneByKv("username", name);
        if (users != null) {
            return Result.fail("手机号已被注册");
            //throw new IFastApiException(ApiEnumError.USERNAMEEXISTED.getCodeStr());
        } else {
          /*  // 校验验证码是否失效
            boolean verifyCode = smsService.verifyCode(O_REG_SMS_PREFIX, mobile);
            if (verifyCode) {
                return Result.build(EnumErrorCode.userLoginFai1l2.getCode(), EnumErrorCode.userLoginFai1l2.getMsg());
            }
            //校验验证码
            try {
                smsService.verify(O_REG_SMS_PREFIX, mobile, code);
            } catch (Exception e) {
                throw new IFastApiException(ApiEnumError.apiSmsCodeInvalid.getCodeStr());
            }*/
            UserDO userDO = new UserDO();
            userDO.setPassword(password);
            userDO.setUsername(mobile);
            userDO.setName(name);
            userDO.setWxId(103);
            userDO.setMobile(mobile);

            userDO.setMoney(BigDecimal.valueOf(0.0));//默认0元
            userDO.setGmtCreate(new Date());
            userDO.setStatus(1);//默认正常
            userDO.setSex(0L);//默认未知

            EntityWrapper<RoleDO> roleDOEntityWrapper = new EntityWrapper<>();

            //判断类型 - 3教师  5学生
            if (type.equals("3")) {
                userDO.setType(Integer.valueOf(type));
                userDO.setStudentId(num);
                roleDOEntityWrapper.eq("roleName","教师");
            } else if (type.equals("5")) {
                userDO.setType(Integer.valueOf(type));
                userDO.setStudentId(num);
                roleDOEntityWrapper.eq("roleName","学生");
            } else {
                throw new IFastApiException(ApiEnumError.TYPEERROR.getCodeStr());
            }

            boolean b = userService.insert(userDO);

            // 查询角色
            RoleDO roleDO = roleService.selectOne(roleDOEntityWrapper);

            // 向权限表中插入信息
            UserRoleDO userRoleDO = new UserRoleDO();
            userRoleDO.setUserId(userDO.getId());
            userRoleDO.setRoleId(roleDO.getId());
            // 新增用户权限关联
            userRoleService.insert(userRoleDO);

            if (b) {
                // 注册成功，进行登录
                //String pass = MD5Utils.convertMD5(password);
                UsernamePasswordToken token = new UsernamePasswordToken(userDO.getUsername(), password);
                Subject subject = SecurityUtils.getSubject();

                subject.login(token);
                UserDO userDOs = (UserDO) subject.getPrincipals().getPrimaryPrincipal();

                //根据手机号码生成自定义登录态
                TokenVO returnToken = userService.getToken(userDO.getMobile());
                //将生成的登录态和手机号码关联，并存到缓存中
                Map cache = new HashMap();
                cache.put("mobile", mobile);
                EhCacheUtil.put(returnToken.getToken(), cache);
                //返回登录态和用户信息
                Map<String, Object> map = new HashMap<>();
                map.put("token", returnToken.getToken());
                map.put("userName", userDO.getUsername());
                map.put("type", userDO.getType());
                map.put("userId", userDO.getId());
                map.put("mobile", userDO.getMobile());
                map.put("uName", userDO.getName());
                List<MsgDO> msg = msgService.findByKv("state", 0, "userId", userDO.getId(), "type", 0);
                List<MsgDO> msg1 = msgService.findByKv("state", 0, "userId", userDO.getId(), "type", 1);
                map.put("unreadNum0", msg.size());
                map.put("unreadNum1", msg1.size());
                request.getSession().setAttribute("userName", userDO.getUsername());

                return Result.ok(map);

            } else {
                return Result.fail("注册失败");
            }

        }
    }


    /**
     * 工号修改
     */
    @PostMapping("editJobNum")
    @ApiOperation(value = "修改工号", notes = "修改工号")
    @ApiResponses({@ApiResponse(code = 0, message = "操作成功"), @ApiResponse(code = 500, message = "服务器内部异常")})
    @ResponseBody
    public Result editJobNum(String id, String num) {
        // 校验参数
        if (StringUtils.isEmpty(num)) {
            return Result.build(500, "工号不能为空");
        }
        // 查询用户信息
        EntityWrapper<UserDO> wrapper = new EntityWrapper<>();
        wrapper.eq("id", id);
        UserDO userDO = userService.selectOne(wrapper);
        if (userDO == null) {
            return Result.build(500, "账号不存在,无法修改");
        }

        // 查询修改的工号信息
        String[] listStudentId = userService.listStudentId();
        for (String studentId : listStudentId) {
            if (studentId.equals(num)) {
                return Result.build(500, "工号重复，请重新输入");
            }
        }

        // 根据id修改
        userDO.setStudentId(num);
        // 修改
        boolean b = userService.updateById(userDO);
        if (b) {
            return Result.ok("修改成功");
        } else {
            return Result.fail("修改失败");
        }
    }


    /**
     * 手机号修改
     */
    @PostMapping("/editPhone")
    @ResponseBody
    @ApiOperation(value = "修改手机号", notes = "修改手机号")
    @ApiResponses({@ApiResponse(code = 0, message = "操作成功"), @ApiResponse(code = 500, message = "服务器内部异常")})
    /*Result<?> editPhone(String id, String mobile, String code) {*/
    Result<?> editPhone(String id, String mobile) {
        // 判断手机号是否为空
        if (StringUtils.isEmpty(mobile)) {
            return Result.fail("手机号不能为空！");
        }
        //根据id查询用户信息
        UserDO userDO = userService.selectById(id);
        if (userDO == null) {
            return Result.build(500, "账号不存在,无法修改");
        }
        // 根据要修改的手机号查询是否已经存在用户信息
        EntityWrapper<UserDO> wrapper = new EntityWrapper<>();
        wrapper.eq("mobile", mobile);
        UserDO user = userService.selectOne(wrapper);
        if (user != null) {
            return Result.build(500, "修改失败,手机号已注册");
        }

        /*if (StringUtils.isBlank(code)) {
            return Result.build(EnumErrorCode.userLoginFai1l4.getCode(), EnumErrorCode.userLoginFai1l4.getMsg());
        } else {
            // 校验验证码是否失效
            boolean verifyCode = smsService.verifyCode(O_REG_SMS_PREFIX, mobile);
            if (verifyCode) {
                return Result.build(EnumErrorCode.userLoginFai1l2.getCode(), EnumErrorCode.userLoginFai1l2.getMsg());
            }
            //第二步，判断验证码
            try {
                smsSerevice.verify(O_REG_SMS_PREFIX, mobile, code);
            } catch (Exception e) {
                return Result.build(ApiEnumError.apiSmsCodeInvalid.getCode(), ApiEnumError.apiSmsCodeInvalid.getMsg());
            }
            // 修改手机号
            userDO.setMobile(mobile);

            boolean b = userService.updateById(userDO);
            if (b) {
                return Result.ok("修改成功");
            } else {
                return Result.fail("修改失败");
            }
        }*/

        // 修改手机号
        userDO.setMobile(mobile);

        boolean b = userService.updateById(userDO);
        if (b) {
            return Result.ok("修改成功");
        } else {
            return Result.fail("修改失败");
        }

    }


    @Log("跳转注册页面")
    @GetMapping("/registerWeb")
    String registerWeb(Model model) {
        //注册须知
        Wrapper<ConsultationsDO> consultationsDOWrapper = new EntityWrapper<ConsultationsDO>().orderBy("creater_date", false);
        consultationsDOWrapper.eq("first_column", "证书考试门户");
        consultationsDOWrapper.eq("state", 1);
        consultationsDOWrapper.eq("second_column", "注册须知").last("limit 1"); //只查询1条

        List<ConsultationsDO> consultationsDOList = consultationsService.selectList(consultationsDOWrapper);

        model.addAttribute("consultations", consultationsDOList);
        return "certificateWeb/registerWeb";
    }

    /**
     * 微信扫码登录
     * @param model
     * @return
     */
    @Log("跳转到微信扫码登录")
    @GetMapping("/scanCode")
    String scanCode(Model model) {
        String codeimg = null;

        try {
            //微信回调
            String urlString = URLEncoder.encode("https://www.jz1x.com/jzApi/wximgCode/wxlogCode", "utf-8");
            codeimg = "https://open.weixin.qq.com/connect/qrconnect?appid=wxa5b743d1daed59cc&redirect_uri=" + urlString + "&response_type=code&scope=snsapi_login&state=e97555458779708b99b9d40cb49f54245c7500e536445d32#wechat_redirect";

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //注册须知
        Wrapper<ConsultationsDO> consultationsDOWrapper = new EntityWrapper<ConsultationsDO>().orderBy("creater_date", false);
        consultationsDOWrapper.eq("first_column", "证书考试门户");
        consultationsDOWrapper.eq("state", 1);
        consultationsDOWrapper.eq("second_column", "注册须知").last("limit 1"); //只查询1条

        List<ConsultationsDO> consultationsDOList = consultationsService.selectList(consultationsDOWrapper);

        model.addAttribute("consultations", consultationsDOList);
        model.addAttribute("url", codeimg);
        return "certificateWeb/scanDode";
    }

    @Log("跳转手机注册页面")
    @GetMapping("/registerMobileWeb")
    String registerMobileWeb(Model model) {
        //注册须知
        Wrapper<ConsultationsDO> consultationsDOWrapper = new EntityWrapper<ConsultationsDO>().orderBy("creater_date", false);
        consultationsDOWrapper.eq("first_column", "证书考试门户");
        consultationsDOWrapper.eq("state", 1);
        consultationsDOWrapper.eq("second_column", "注册须知").last("limit 1"); //只查询1条

        List<ConsultationsDO> consultationsDOList = consultationsService.selectList(consultationsDOWrapper);

        model.addAttribute("consultations", consultationsDOList);
        return "certificateWeb/registerMobileWeb";
    }


    @Log("忘记密码")
    @GetMapping("/forgetPass")
    String forgetPass() {  //忘记密码
        return "certificateWeb/forgetPass";
    }

    @Log("跳转考核站点申请记录页面")
    @GetMapping("/stationRecordList")
    String stationRecordList() {
        return "certificateWeb/personalCenter/stationRecord";
    }

    @Log("跳转表单提交记录页面")
    @GetMapping("/infoRecordList")
    String infoRecordList() {
        return "certificateWeb/personalCenter/infoRecord";
    }

    @Log("官网填写简历页面")
    @GetMapping("/isResume")
    String isResume() {
        return "certificateWeb/personalCenter/isResume";
    }


    @Log("官网填写简历页面")
    @GetMapping("/appendResume")
    String appendResume() {
        return "certificateWeb/personalCenter/appendResume";
    }

    @Log("官网查看简历页面")
    @GetMapping("/iResume")
    String iResume() {
        return "certificateWeb/personalCenter/iResume";
    }

    @Log("跳转培训站点申请记录页面")
    @GetMapping("/stationPxRecordList")
    String stationPxRecordList() {
        return "certificateWeb/personalCenter/stationPxRecord";
    }

    @Log("跳转申请记录页面")
    @GetMapping("/expertRecordList")
    String expertRecordList() {
        return "certificateWeb/personalCenter/expertRecord";
    }

    @Log("跳转个人中心页面")
    @GetMapping("/my")
    String my() {
        return "certificateWeb/personalCenter/myCenter";
    }

    @Log("跳转消息中心页面")
    @GetMapping("/message")
    @RequiresAuthentication
    String message() {
        return "certificateWeb/personalCenter/message";
    }

    @Log("跳转模拟考试页面")
    @GetMapping("/mock")
    String mock(Model model, String grade) {
        model.addAttribute("grade", grade);
        return "certificateWeb/personalCenter/mockExam";
    }

    @Log("跳转产后恢复模拟考试页面")
    @GetMapping("/recoverMock")
    String recoverMock(Model model, String grade) {
        model.addAttribute("grade", grade);
        return "certificateWeb/personalCenter/recoverMock";
    }

    @Log("编辑个人信息")
    @GetMapping("/editMy")
    String editMy(Model model) {
        model.addAttribute("certificateProfile", certificateNewsService.selByProfileId());
        return "certificateWeb/personalCenter/editMy";
    }

    @Log("跳转专家申请页面")
    @GetMapping("/evaluationStationApplyFor")
    String evaluationStationApplyFor(Model model, Integer type) {
        Wrapper<ConsultationsDO> consultationsDOWrapper = new EntityWrapper<ConsultationsDO>().orderBy("creater_date", false);
        consultationsDOWrapper.eq("first_column", "证书考试门户");
        consultationsDOWrapper.eq("state", 1);
        if (type == 0) {
            consultationsDOWrapper.eq("second_column", "考评员申请模板").last("limit 1"); //只查询1条
        }
        if (type == 1) {
            consultationsDOWrapper.eq("second_column", "考务员申请模板").last("limit 1"); //只查询1条
        }
        if (type == 3) {
            consultationsDOWrapper.eq("second_column", "督导员申请模板").last("limit 1"); //只查询1条
        }
        if (type == 4) {
            consultationsDOWrapper.eq("second_column", "讲师申请模板").last("limit 1"); //只查询1条
        }
        if (type == 2) {
            consultationsDOWrapper.eq("second_column", "考务技术员申请模板").last("limit 1"); //只查询1条
        }
        List<ConsultationsDO> consultationsDOList = consultationsService.selectList(consultationsDOWrapper);
        model.addAttribute("consultations", consultationsDOList);
        model.addAttribute("type", type);
        return "certificateWeb/stationApplyFor/evaluationStationApplyFor";
    }

    @Log("移动端专家申请页面")
    @GetMapping("/evaluationMobileFor")
    String evaluationMobileFor(Model model, Integer type) {
        Wrapper<ConsultationsDO> consultationsDOWrapper = new EntityWrapper<ConsultationsDO>().orderBy("creater_date", false);
        consultationsDOWrapper.eq("first_column", "证书考试门户");
        consultationsDOWrapper.eq("state", 1);
        if (type == 0) {
            consultationsDOWrapper.eq("second_column", "考评员申请模板").last("limit 1"); //只查询1条
        }
        if (type == 1) {
            consultationsDOWrapper.eq("second_column", "考务员申请模板").last("limit 1"); //只查询1条
        }
        if (type == 3) {
            consultationsDOWrapper.eq("second_column", "督导员申请模板").last("limit 1"); //只查询1条
        }
        if (type == 4) {
            consultationsDOWrapper.eq("second_column", "讲师申请模板").last("limit 1"); //只查询1条
        }
        if (type == 2) {
            consultationsDOWrapper.eq("second_column", "考务技术员申请模板").last("limit 1"); //只查询1条
        }
        List<ConsultationsDO> consultationsDOList = consultationsService.selectList(consultationsDOWrapper);
        model.addAttribute("consultations", consultationsDOList);
        model.addAttribute("type", type);
        return "certificateWeb/stationApplyFor/evaluationMobileFor";
    }

    @Log("跳专家编辑页面")
    @GetMapping("/editExpert")
    String editExpert(Model model, String id) {
        ExpertsDO experts = expertsService.selectById(id);
        Wrapper<ConsultationsDO> consultationsDOWrapper = new EntityWrapper<ConsultationsDO>().orderBy("creater_date", false);
        consultationsDOWrapper.eq("first_column", "证书考试门户");
        consultationsDOWrapper.eq("state", 1);
        if (experts.getType() == 0) {
            consultationsDOWrapper.eq("second_column", "考评员申请模板").last("limit 1"); //只查询1条
        }
        if (experts.getType() == 1) {
            consultationsDOWrapper.eq("second_column", "考务员申请模板").last("limit 1"); //只查询1条
        }
        if (experts.getType() == 3) {
            consultationsDOWrapper.eq("second_column", "督导员申请模板").last("limit 1"); //只查询1条
        }
        if (experts.getType() == 4) {
            consultationsDOWrapper.eq("second_column", "讲师申请模板").last("limit 1"); //只查询1条
        }
        if (experts.getType() == 2) {
            consultationsDOWrapper.eq("second_column", "考务技术员申请模板").last("limit 1"); //只查询1条
        }
        List<ConsultationsDO> consultationsDOList = consultationsService.selectList(consultationsDOWrapper);
        model.addAttribute("consultations", consultationsDOList);
        UserDO user = userService.getByUserId(experts.getUserId());
        model.addAttribute("user", user);
        model.addAttribute("expert", experts);
        model.addAttribute("certificateProfile", certificateNewsService.selByProfileId());
        model.addAttribute("id", id);
        return "certificateWeb/stationApplyFor/editExpert";
    }


    @Log("报名成功")
    @GetMapping("/applySuccess")
    String applySuccess(Model model, String signId, String chatchId) {
        model.addAttribute("chatchId", chatchId);
        model.addAttribute("signId", signId);
        return "certificateWeb/onLineApply/applySuccess";
    }

    @Log("查看准考证页面")
    @GetMapping("/examCard")
    String examCard(Model model, String id) {
        model.addAttribute("id", id);
        return "certificateWeb/personalCenter/ExamCard";
    }

    @Log("退出登录")
    @GetMapping("/loginOut")
    @ResponseBody
    Result<?> loginOut() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return Result.ok();
    }


    @Log("查询机构信息")
    @GetMapping("/findByOrg")
    String findByOrg(Model model, String orgId) {
        model.addAttribute("orgId", orgId);
        return "certificateWeb/personalCenter/orgInfo";
    }

    @Autowired
    private SmsLimitService smsLimitService;


    @PostMapping("/sendRegCode")
    @Log("发送注册验证短信")
    @ApiOperation(value = "发送注册验证短信", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public ApiResult<?> sendRegCode(String mobile) {
        // 校验发送验证码的次数
        if (smsLimitService.checkCount(mobile)) {
            return ApiResult.fail("今日验证码已达5次，请明日再试");
        } else {
            smsLimitService.incrementCount(mobile);
        }

        //第一步验证手机号格式
        if (StringUtils.isBlank(mobile)) {
            return ApiResult.lack("mobile");
        }
        if (!ValidUtils.isMobile(mobile)) {
            return ApiResult.format("mobile");
        }

        Object smsDemo = EhCacheUtil.get("注册短信验证");
        if (smsDemo == null) {
            MessageplatfromDO messageplatfromDO = messageplatfromService.findOneByKv("注册短信验证");
            if (messageplatfromDO != null) {
                EhCacheUtil.put("注册短信验证", messageplatfromDO.getSmsDemo());
                smsService.sendreg(O_REG_SMS_PREFIX, mobile, messageplatfromDO.getSmsDemo());
            } else {
                return ApiResult.fail("短信模板错误，请联系管理员！");
            }
        } else {
            smsService.sendreg(O_REG_SMS_PREFIX, mobile, (String) smsDemo);
        }

        return ApiResult.success("发送成功");
    }

    /**
     * 微信扫码绑定 手机号
     *
     * @param mobile
     * @return
     */
    @PostMapping("/sendRegCodeWx")
    @Log("发送注册验证短信")
    @ApiOperation(value = "发送注册验证短信", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public ApiResult<?> sendRegCodeWx(String mobile) {
        //第一步验证手机号格式
        if (StringUtils.isBlank(mobile)) {
            return ApiResult.lack("mobile");
        }
        if (!ValidUtils.isMobile(mobile)) {
            return ApiResult.format("mobile");
        }

        Object smsDemo = EhCacheUtil.get(mobile + "wxCode");
        if (smsDemo == null) {
            MessageplatfromDO messageplatfromDO = messageplatfromService.findOneByKv("微信绑定短信验证");
            if (messageplatfromDO != null) {
                EhCacheUtil.put(mobile + "wxCode", messageplatfromDO.getSmsDemo());
                smsService.sendreg(O_REG_SMS_PREFIX, mobile, messageplatfromDO.getSmsDemo());

            } else {
                return ApiResult.fail("短信模板错误，请联系管理员！");
            }
        } else {
            smsService.sendreg(O_REG_SMS_PREFIX, mobile, (String) smsDemo);
        }

        return ApiResult.success("发送成功");
    }


    @Log("查询对应证书的知识点")
    @GetMapping("/findKonwledge")
    @ResponseBody
    public ApiResult<?> findKonwledge(String profileId) {
        List<KnowledgePointsDO> knowList = knowledgePointsService.findByKv("profile_id", profileId, "state", 0);
        return ApiResult.success(knowList);
    }

    @Log("试点院校风采")
    @GetMapping("/schoolMien")
    String schoolMien(Model model) {
        return "certificateWeb/tradeInfo/schoolMien";
    }

    @Log("移动端试点院校风采")
    @GetMapping("/schoolMienMobile")
    String schoolMienMobile(Model model) {
        return "certificateWeb/tradeInfo/schoolMienMobile";
    }

    @Log("考试流程介绍")
    @PostMapping("/examIntroduce")
    @ResponseBody
    Result<?> examIntroduce() {
        ConsultationsDO conDo = consultationsService.findOneByKv("second_column", "考试流程介绍");
        return Result.ok(conDo);
    }

    /**
     * 下载导入模板
     *
     * @param response
     */
    @RequestMapping("/download")
    @ResponseBody
    public void downloadImportTemplate(HttpServletResponse response, Integer type) {
        List<TrainingBaseVo> list = new LinkedList<>();
        if (type == 5) {//导出操作
            EasyPoiUtil.exportExcel(list, "实习就业单位信息导入模板", "实习就业单位信息导入模板", TrainingBaseVo.class, "实习就业单位信息导入模板", response);
        } else {
            EasyPoiUtil.exportExcel(list, "校企合作信息导入模板", "校企合作信息导入模板", TrainingBaseVo.class, "校企合作信息导入模板", response);
        }

//		EasyPoiUtil.exportExcel(list, "实习就业单位信息导入模板", "实习就业单位信息导入模板", TrainingBaseVo.class, "实习就业单位信息导入模板", response);
    }


}
